package com.atguigu.redis.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther zzyy
 * @create 2021-05-02 18:16
 */
@Api(description = "案例实战总02:统计一个用户每个月的签到情况")
@RestController
@Slf4j
public class BitMapController
{

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("统计一个用户每个月的签到情况")
    @RequestMapping(value = "/sign",method = RequestMethod.GET)
    public Map sign()
    {
        //pfcount
        Map<String, Boolean> res = new HashMap<>();
        for (int i = 1; i <=31; i++) {
            res.put(String.valueOf(i), redisTemplate.opsForValue().getBit("sign:uid00001:202112", i));
        }
        return res;
    }

    @ApiOperation("签到总次数")
    @RequestMapping(value = "/count",method = RequestMethod.GET)
    public long count()
    {
        return (long) redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount("sign:uid00001:202112".getBytes()));
    }

    @ApiOperation("用户连续签到次数")
    @RequestMapping(value = "/bitfield",method = RequestMethod.GET)
    public List<Long> bitfield()
    {
        return (List<Long>) redisTemplate.execute((RedisCallback<List<Long>>) con ->
                con.bitField("sign:uid00001:202112".getBytes(),
                        BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(1)).valueAt(5)));
    }

}
